package com.srpingde.hhh;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.springde.hhh.R;
import com.srpingde.hhh.application.HhhApp;
import com.srpingde.hhh.application.HHHDataManage;
import com.srpingde.hhh.bean.GouWuChe;
import com.srpingde.hhh.bean.GouWuCheDataBean;
import com.srpingde.hhh.http.AsyncHttpResponseHandler;
import com.srpingde.hhh.jiekou.HHHIml;
import com.srpingde.hhh.jiekou.HHHInterface;

public class GouWuCheActivity extends Activity {
	public static ListView listView;
	public static GouWuCheAdapter adapter;
	HashMap<String, String> hashMap;
	public static GouWuChe gouWuChe;
	List<GouWuChe> list;
	AlertDialog dialog;
	ImageView back;
	List<Integer> shuliang;
	List<Integer> ids;
	List<String> type;
	public static ArrayList<Integer> position;
	HHHIml weiQuIml;
	TextView gouwuche_show_jiage;
	List<Boolean>  ischeck;	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gou_wu_che);
		listView = (ListView) findViewById(R.id.gouwuche_lv);
		back = (ImageView) findViewById(R.id.back);
		gouwuche_show_jiage = (TextView) findViewById(R.id.gouwuche_show_jiage);
		hashMap = new HashMap<String, String>();
		this.position = new ArrayList<Integer>();
		this.shuliang = new ArrayList<Integer>();
		this.type = new ArrayList<String>();
		this.ids = new ArrayList<Integer>();
		this.ischeck=new ArrayList<Boolean>();
		layout();
		list = new ArrayList<GouWuChe>();
		weiQuIml = new HHHIml();
		String url = HHHInterface.httpHeader + "api.php?tab=cart&act=data&uid="+ HhhApp.getInstance().getUid() + "&pagesize=100&page=1";
		weiQuIml.gouWuCheHttp(url, GouWuCheActivity.this,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(String content) {
						// TODO Auto-generated method stub
						super.onSuccess(content);
						gouWuChe = HHHDataManage.getInstance().getGouWuChe();
						adapter = new GouWuCheAdapter(GouWuCheActivity.this,gouWuChe.getRows());
						for(int i=0;i<gouWuChe.getRows().size();i++){
							ischeck.add(true);
						}
						listView.setAdapter(adapter);
					}
				});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(GouWuCheActivity.this)
				.setTitle("提示").setMessage("确定要删除吗？")
				.setPositiveButton("确定",new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,int which) {
								// TODO Auto-generated method stub
								delete(gouWuChe.getRows().get(arg2).getPid(),gouWuChe.getRows().get(arg2).getStyle());
								gouWuChe.getRows().remove(arg2);
								 adapter.notifyDataSetChanged();
							}
						}).setNegativeButton("取消", null).create().show();
				return false;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent in= new Intent(GouWuCheActivity.this,XiangQingActivity.class);
				in.putExtra("id", gouWuChe.getRows().get(arg2).getPid());
				startActivity(in);
			}
		});
	}
	// 收藏
	private void collection(String pid) {
		String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=add&uid="
				+ HhhApp.getInstance().getUid() + "&type=1&pid=" + pid;
		weiQuIml.loginHttp(GouWuCheActivity.this, url,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content + "================收藏返回的数据");
						try {
							JSONObject jsonObject = new JSONObject(content);
							if (jsonObject.getBoolean("return")) {
								HhhApp.getInstance().showDialog(GouWuCheActivity.this, "收藏成功");
							} else {
								HhhApp.getInstance().showDialog(GouWuCheActivity.this, "已经收藏过了");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}

	public void delete(String pid,String style) {
		String str = HHHInterface.httpHeader + "api.php?tab=cart&act=del&pid="
				+ pid + "&uid=" + HhhApp.getInstance().getUid() + "&style=" + style;
		Log.e("删除", "pid"+pid+"uid"+HhhApp.getInstance().getUid());
		weiQuIml.gouWuChedeleteHttp(str, GouWuCheActivity.this,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content + "================收藏返回的数据");
						try {
							JSONObject jsonObject = new JSONObject(content);
							if (jsonObject.getBoolean("return")) {
								//WeiQuApp.getInstance().showDialog(GouWuCheActivity.this, "删除成功");
								Intent intent = new Intent(GouWuCheActivity.this,GouWuCheActivity.class);
								startActivity(intent);
								GouWuCheActivity.this.finish();
							} else {
								HhhApp.getInstance().showDialog(GouWuCheActivity.this, "删除失败");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}
	
	public void delete2(String pid,String style) {
		String str = HHHInterface.httpHeader + "api.php?tab=cart&act=del&pid="
				+ pid + "&uid=" + HhhApp.getInstance().getUid() + "&style=" + style;
		Log.e("删除", "pid"+pid+"uid"+HhhApp.getInstance().getUid());
		weiQuIml.gouWuChedeleteHttp(str, GouWuCheActivity.this,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content + "================收藏返回的数据");
						try {
							JSONObject jsonObject = new JSONObject(content);
							if (jsonObject.getBoolean("return")) {
								//WeiQuApp.getInstance().showDialog(GouWuCheActivity.this, "删除成功");
							} else {
								HhhApp.getInstance().showDialog(GouWuCheActivity.this, "删除失败");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.jiesuan:
			Log.e("mytag", getContent() + "-=======转成json得到的string");
			if(!getContent().equals("[]")){	
				Intent in = new Intent(GouWuCheActivity.this,ShouHuoListActivity.class);
				in.putExtra("content", getContent());
				startActivity(in);		
				GouWuCheActivity.this.finish();
			}else{
				HhhApp.getInstance().showDialog(this, "请选择要购买的商品");
			}
			break;
		case R.id.back:
			finish();
			break;
		}
	}

	private void layout() {
		// 头的高度
		TextView top_title_tv = (TextView) findViewById(R.id.top_title);
		RelativeLayout.LayoutParams titleLayoutParams = (android.widget.RelativeLayout.LayoutParams) top_title_tv.getLayoutParams();
		titleLayoutParams.height = HhhApp.getInstance().title_h();
		top_title_tv.setLayoutParams(titleLayoutParams);
		RelativeLayout.LayoutParams backLayoutParams = (LayoutParams) back.getLayoutParams();
		backLayoutParams.height = HhhApp.getInstance().title_h();
		back.setLayoutParams(backLayoutParams);
	}

	class GouWuCheAdapter extends BaseAdapter {
		String style1;
		Context context;
		int num = 1;
		int jiage;
		List<GouWuCheDataBean> list;
		java.util.Map<String, Integer> map;

		public GouWuCheAdapter(Context context, List<GouWuCheDataBean> list) {
			super();
			this.context = context;
			this.list = list;
			this.map = new HashMap<String, Integer>();
			for(GouWuCheDataBean gouWuChe : this.list){
				Log.e("价格", "jiage:"+gouWuChe.getPrice()+"     数量:"+Integer.valueOf(gouWuChe.getAmount()));
				jiage = jiage +(Integer.valueOf(gouWuChe.getPrice())*Integer.valueOf(gouWuChe.getAmount()));
				shuliang.add(Integer.valueOf(gouWuChe.getAmount()));
				type.add(gouWuChe.getStyle());
				ids.add(Integer.valueOf(gouWuChe.getPid()));
			}
			gouwuche_show_jiage.setText(String.valueOf(jiage));
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			arg1 = LayoutInflater.from(context).inflate(R.layout.gouwuche_item,null);
			CheckBox checkBox = (CheckBox) arg1.findViewById(R.id.gouwuche_checkbox);
			ImageView show_icon = (ImageView) arg1.findViewById(R.id.gouwuche_iv);
			final Button show_shuliang = (Button) arg1.findViewById(R.id.gouwuche_show_shuliang);
			final TextView style = (TextView) arg1.findViewById(R.id.gouwuche_style);
			TextView more = (TextView) arg1.findViewById(R.id.gouwuche_more);
			TextView mingche=(TextView) arg1.findViewById(R.id.gouwuche_mingche);
			TextView price=(TextView) arg1.findViewById(R.id.gouwuche_price);
			TextView baoyou=(TextView) arg1.findViewById(R.id.baoyou);
			final GouWuCheDataBean gouWuChe = list.get(arg0);
			mingche.setText(gouWuChe.getName());
			show_shuliang.setText(gouWuChe.getAmount());
			checkBox.setFocusable(false);
			checkBox.setChecked(ischeck.get(arg0));
			position.add((Integer)arg0);
			show_shuliang.setFocusable(false);
			style.setText(gouWuChe.getStyle());
			price.setText(gouWuChe.getPrice());
			final ImageView kvShow = show_icon;
			ImageLoader.getInstance().loadImage(HHHIml.httpHeader + gouWuChe.getUrl(),new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,View view, Bitmap bitmap) {
							BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
							kvShow.setBackgroundDrawable(bitmapDrawable);
						}
					});
			checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					if (isChecked) {
						ischeck.set(arg0, true);
						jiage = (Integer) jiage + (Integer.valueOf(gouWuChe.getPrice())*Integer.valueOf(gouWuChe.getAmount()));
						shuliang.add(Integer.valueOf(show_shuliang.getText().toString()));
						type.add(gouWuChe.getStyle());
						ids.add(Integer.valueOf(gouWuChe.getPid()));
						position.add((Integer)arg0);
					} else {
						ischeck.set(arg0, false);
						jiage = (Integer) jiage -(Integer.valueOf(gouWuChe.getPrice())*Integer.valueOf(gouWuChe.getAmount()));
						shuliang.remove(Integer.valueOf(show_shuliang.getText().toString()));
						ids.remove(Integer.valueOf(gouWuChe.getPid()));
						type.remove(gouWuChe.getStyle());
						position.remove((Integer)arg0);
					}
					gouwuche_show_jiage.setText(String.valueOf(jiage));
				}
			});
			
			if(!checkBox.isChecked()){
				ischeck.set(arg0, false);
				jiage = (Integer) jiage -(Integer.valueOf(gouWuChe.getPrice())*Integer.valueOf(gouWuChe.getAmount()));
				shuliang.remove(Integer.valueOf(show_shuliang.getText().toString()));
				ids.remove(Integer.valueOf(gouWuChe.getPid()));
				type.remove(gouWuChe.getStyle());
				gouwuche_show_jiage.setText(String.valueOf(jiage));
				position.remove((Integer)arg0);
			}
			
			show_shuliang.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					// TODO Auto-generated method stub
					View view = LayoutInflater.from(context).inflate(R.layout.gouwuche_num_dialog, null);
					ImageView add = (ImageView) view.findViewById(R.id.shuliang_add);
					style1 = style.getText().toString();
					final TextView show = (TextView) view.findViewById(R.id.shuliang_show);
					num = (int) (Integer.valueOf(show_shuliang.getText().toString()));
					show.setText(num + "");
					add.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							num++;
							show.setText(num + "");
							show_shuliang.setText(num + "");
							
						}
					});
					ImageView jian = (ImageView) view.findViewById(R.id.shuliang_jian);
					jian.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							num--;
							if (num <= 0) {
								num = 1;
							}
							show.setText(num + "");
							show_shuliang.setText(num + "");
						}
					});
					new AlertDialog.Builder(context).setView(view).setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,int which) {
											// TODO Auto-generated method stub
											addToGouWuChe(gouWuChe.getPid(),num,style1);
											jiage = 0;
											shuliang.clear();
											type.clear();
											ids.clear();
											position.clear();
											num = 0;
										}
									}).create().show();
				}
			});
			return arg1;
		}

		class GouWuCheAdapterHolder {
			CheckBox checkBox;
			ImageView show_icon;
			TextView show_shuliang;
			TextView more;
		}
	}
	
	  public void addToGouWuChe(String id,int amount,String style){
	    	String url = HHHInterface.httpHeader + "api.php?tab=cart&act=edit&pid="+id+"&uid="+HhhApp.getInstance().getUid()+"&amount="+amount + "&style=" + style;
	    	Log.e("mytag", url+"=========款式");
	    	weiQuIml.gouWuCheAddHttp(GouWuCheActivity.this,url, new AsyncHttpResponseHandler(){
				@Override
				public void onSuccess(String content) {
					super.onSuccess(content);
					Log.e("mytag", content+"================数量更改返回的数据");
					try {
						JSONObject jsonObject = new JSONObject(content);
						if(jsonObject.getBoolean("return")){
							HhhApp.getInstance().showDialog(GouWuCheActivity.this, "更改成功");
							String url = HHHInterface.httpHeader + "api.php?tab=cart&act=data&uid="+ HhhApp.getInstance().getUid() + "&pagesize=100&page=1";
							weiQuIml.gouWuCheHttp(url, GouWuCheActivity.this,
									new AsyncHttpResponseHandler() {

										@Override
										public void onSuccess(String content) {
											// TODO Auto-generated method stub
											super.onSuccess(content);
											gouWuChe = HHHDataManage.getInstance().getGouWuChe();
											//gouwuche_yunfei.setText("运费:" + gouWuChe.getYunfei());
											adapter = new GouWuCheAdapter(GouWuCheActivity.this,gouWuChe.getRows());
											listView.setAdapter(adapter);
										}
									});
						}else if(!jsonObject.getBoolean("return")){
							HhhApp.getInstance().showDialog(GouWuCheActivity.this, "更改失败");
						}else{
							HhhApp.getInstance().showDialog(GouWuCheActivity.this, "更改失败");
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});	
	    }
	
	public String getContent() {
		JSONArray jsonArray = new JSONArray();
		try {
			for (int i = 0; i < ids.size(); i++) {
				JSONObject jsonPeopleNumbers = new JSONObject();
				jsonPeopleNumbers.put("shopID", ids.get(i));
				jsonPeopleNumbers.put("style", type.get(i));
				jsonPeopleNumbers.put("number", shuliang.get(i));
				jsonArray.put(jsonPeopleNumbers);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonArray.toString();
	}
}
